package mbms.mobilebudget;

import java.sql.SQLException;
import java.util.List;

import mbms.mobilebudget.bankaccount.BankAccountsActivity;
import mbms.mobilebudget.creditCard.CreditCardsActivity;
import mbms.mobilebudget.database.DatabaseHandler;
import mbms.mobilebudget.entity.CurrencyRate;
import mbms.mobilebudget.entity.EnumValues.CurrencyType;
import mbms.mobilebudget.entity.Exchange;
import mbms.mobilebudget.entity.User;
import mbms.mobilebudget.exchangerateservice.CurrencyRateParser;
import mbms.mobilebudget.exchangerateservice.CurrencyRateRequestTask;
import mbms.mobilebudget.expense.ExpensesActivity;
import mbms.mobilebudget.income.BankAccountCreditCardListActivity;
import mbms.mobilebudget.income.IncomesActivity;
import mbms.mobilebudget.overview.OverviewActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.Dao;

public class OperationsActivity extends OrmLiteBaseActivity<DatabaseHandler> {

	private User user;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_operations);
		Intent intent = getIntent();
		user = (User) intent.getSerializableExtra("loggedInUser");
		if(user==null){
			Toast.makeText(getApplicationContext(), 
					"User not acquired", Toast.LENGTH_LONG).show();
			return ;
		}
		try {
			Dao<Exchange,Integer> exchangeDao = getHelper().getExchangeDao();
			List<Exchange> rates = exchangeDao.queryForAll();
			if(rates==null || rates.isEmpty()){
				exchangeDao.create(new Exchange(null, 85.00, 1.88, 2.45));
				Exchange ew=	exchangeDao.queryForId(1);
				Log.d("exchange", ""+ew.getDollar()+","+ew.getEuro()+","+ ew.getGold());
			}
		} catch (SQLException e1) {
			Toast.makeText(getApplicationContext(), 
					"Exchange data not created", Toast.LENGTH_SHORT).show();	
			
		}
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.operations, menu);
		getMenuInflater().inflate(R.menu.currency_rate, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
        case R.id.currency_rate:
            runOnUiThread(new Runnable() {
				@Override
				public void run() {
					CurrencyRateRequestTask requestTast = new CurrencyRateRequestTask(OperationsActivity.this);
					requestTast.execute("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair=%22xautry,%20usdtry,%20eurtry%22&format=xml&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
				}
			});
            
            return true;
        default:
            return super.onOptionsItemSelected(item);
		}

	}
	private void updateRates(Double g, Double d, Double e){
		
		try {
			Dao<Exchange,Integer> exchange2Dao = getHelper().getExchangeDao();
			List<Exchange> rates = exchange2Dao.queryForAll();
			if(rates==null || rates.isEmpty()){
				if(d==null)
				{
					d =1.88;
				}
				if(e == null){
					e = 2.45;
				}
				if(g == null){
					g =85.00;
				}
				exchange2Dao.create(new Exchange(null, g, d, e));
			}
			else{
				Exchange ex = rates.get(0);
				if(d==null)
				{
					d =1.88;
				}
				if(e == null){
					e = 2.45;
				}
				if(g == null){
					g =85.00;
				}
				ex.setDollar(d);
				ex.setEuro(e);
				ex.setGold(g);
				exchange2Dao.update(ex);
			}
		} catch (SQLException ee) {
			Toast.makeText(getApplicationContext(), 
					"Error in exchange update", Toast.LENGTH_SHORT).show();
		}
	}
	
	public void redirectIncomes(View view){
		Intent intent = new Intent (this, BankAccountCreditCardListActivity.class);
		if(user==null){
			Toast.makeText(getApplicationContext(), "User not acquired", Toast.LENGTH_LONG).show();
			return ;
		}
		
		intent.putExtra("authenticatedUser", user);
		intent.putExtra("clazz", IncomesActivity.class);
		startActivity(intent);
	}
	
	public void redirectExpenses(View view){
		Intent intent = new Intent (this, BankAccountCreditCardListActivity.class);
		if(user==null){
			Toast.makeText(getApplicationContext(), "User not acquired", Toast.LENGTH_LONG).show();
			return ;
		}
		
		intent.putExtra("authenticatedUser", user);
		intent.putExtra("clazz", ExpensesActivity.class);
		startActivity(intent);
	}
	
	public void redirectBankAccounts(View view){
		Intent intent = new Intent (this, BankAccountsActivity.class);
		if(user==null){
			Toast.makeText(getApplicationContext(), 
					"User not acquired", Toast.LENGTH_LONG).show();
			return ;
		}
		intent.putExtra("loggedInUser", user);
		startActivity(intent);
	}
	
	public void redirectCreditCards(View view){
		Intent intent = new Intent (this, CreditCardsActivity.class);
		if(user==null){
			Toast.makeText(getApplicationContext(), 
					"User not acquired", Toast.LENGTH_LONG).show();
			return ;
		}
		intent.putExtra("loggedInUser", user);
		startActivity(intent);
	}
	
	public void redirectOverview(View view){
		Intent intent = new Intent (this, OverviewActivity.class);
		if(user==null){
			Toast.makeText(getApplicationContext(), 
					"User not acquired", Toast.LENGTH_LONG).show();
			return ;
		}
		intent.putExtra("loggedInUser", user);
		startActivity(intent);
	}

	public void updateCurrencyRates(List<CurrencyRate> currencyRateList) {
		Double gold = null, dollar = null, euro = null;
		if(currencyRateList!=null && currencyRateList.size()==3){
			for (CurrencyRate currencyRate : currencyRateList) {
				if(currencyRate.getFromCurrency().equals(CurrencyType.GOLD)){
					gold = currencyRate.getCurrencyRate();
				}
				else if(currencyRate.getFromCurrency().equals(CurrencyType.DOLLAR)){
					dollar = currencyRate.getCurrencyRate();
				}
				else if(currencyRate.getFromCurrency().equals(CurrencyType.EURO)){
					euro = currencyRate.getCurrencyRate();
				}
			
		}
			
		updateRates(gold, dollar, euro);
	}
	}
}
